package com.lei.emos.wx.config.shiro;


import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import org.apache.http.HttpStatus;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
@Scope("prototype")//变为多例对象
public class OAuth2Filter extends AuthenticatingFilter {

    @Autowired
    private ThreadLocalToken threadLocalToken;

    @Value("${emos.jwt.cache-expire}")
    private int cacheExpire;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 拦截请求之后，用于把令牌字符串封装成令牌对象
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest req = (HttpServletRequest) request;
        //调用私有方法获取token
        String token = getRequestToken(req);
        //判断token是否为空 为空的情况无法封装为token  直接返回null
        if (StrUtil.isBlank(token)){
            return null;
        }
        //token 不为空就调用封装的tokenOAuth2Token
        return new OAuth2Token(token);
    }

    /**
     * 判断请求方法是否是options方法
     * @param request
     * @param response
     * @param mappedValue
     * @return
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        HttpServletRequest req = (HttpServletRequest) request;
        //判断请求方法是不是 options 方法 是就放行 不经过shiro处理
        if (req.getMethod().equals(RequestMethod.OPTIONS.name())){
            return true;
        }
        //如果不是options方法就由shiro处理
        return false;
    }


    /**
     * 该方法用于处理所有应该被Shiro处理的请求
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //设置响应头类型
        resp.setContentType("text/html");
        //设置响应头字符编码
        resp.setCharacterEncoding("UTF-8");
        //应允跨域请求
        resp.setHeader("Access-Control-Allow-Credentials","true");
        resp.setHeader("Access-Control-Allow-Origin",req.getHeader("Origin"));

        //清空threadLocalToken中的数据
        threadLocalToken.clear();

        String token = getRequestToken(req);
        //获取到token后 为空的情况直接返回提示消息
        if (StrUtil.isBlank(token)){
            resp.setStatus(HttpStatus.SC_UNAUTHORIZED);
            resp.getWriter().print("无效的令牌");
            return false;
        }
        try{
            jwtUtil.verifierToken(token);
        }
        //token过期异常捕获
        catch (TokenExpiredException e){
            //判断redis中缓存是否过期
            //如果有 那就说明 客户端过期了 但是 redis没过期 要进行令牌的刷新
            if (redisTemplate.hasKey(token)){
                //删除redis中的token 生成新token
                redisTemplate.delete(token);
                int userId = jwtUtil.getUserId(token);
                token = jwtUtil.createToken(userId);
                //保存ThreadLocalToken和Redis中
                redisTemplate.opsForValue().set(token,userId+"",cacheExpire, TimeUnit.DAYS);
                threadLocalToken.setToken(token);
            }
            //如果redis中和客服端都过期了  需要用户重新登录
            else {
                resp.setStatus(HttpStatus.SC_UNAUTHORIZED);
                resp.getWriter().print("令牌已过期");
                return false;
            }
        }
        //token错误异常捕获 可能伪造的
        catch (JWTDecodeException e){
            resp.setStatus(HttpStatus.SC_UNAUTHORIZED);
            resp.getWriter().print("无效的令牌");
            return false;
        }
        //executeLogin可以间接的让shiro执行Realm类
        boolean result = executeLogin(request, response);
        return result;
    }

    /**
     * 用户登录失败 或者 没有登录就会  执行这个方法
     * 设置返回的状态码 以及信息
     * @param token
     * @param e
     * @param request
     * @param response
     * @return
     */
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //设置响应头类型
        resp.setContentType("text/html");
        //设置响应头字符编码
        resp.setCharacterEncoding("UTF-8");
        //应允跨域请求
        resp.setHeader("Access-Control-Allow-Credentials","true");
        resp.setHeader("Access-Control-Allow-Origin",req.getHeader("Origin"));
        resp.setStatus(HttpStatus.SC_UNAUTHORIZED);
        try {
            resp.getWriter().print(e.getMessage());
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        return false;
    }

    @Override
    public void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        super.doFilterInternal(request, response, chain);
    }

    /**
     * 从请求中获取token
     * @param request
     * @return
     */
    private String getRequestToken(HttpServletRequest request){
        //从请求头中获取token
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)){
            //如果请求头中获取到的token为空 就从请求体中获取
            token = request.getParameter("token");
        }
        return token;
    }
}
